<?php 
$found = false;
$buscar = false;
include('../Connections/KRAPPERCON.php');
include ("../Connections/Accesos.php");

$factid = '';
$faccre  = '';
$facfec  = '';
$usrcre = '';
$facpro = '';
$facven = '';
$facsts = '';
$faccen = '';
$facimp = '';
$factxt = '';
$faccla = '';
$factc = '';
$facmon = '';
$factot = '';
$feccon = '';
$facref = '';
$monexo = 0;
$monitm = 0;
$cl_gasto = '';

//echo str_replace('a','zzz','hola');
//echo "BUSCAR";
$fact = getGet('factura');
	if (trim($fact)!=''){
		$buscar = true;		
		$sql = "call sp_getFactCompCabe('".$fact."');";
		//echo($sql);
		$res = $mysqli->query($sql);
		if ($res){
			if ($row = $res->fetch_assoc()){
				$found = true;				
				$factid = '';
$faccre  = $row['FactCompFeCr'];
$facfec  = $row['FactCompFeFc'];
$usrcre = $row['UserID'];
$facpro = $row['ProveedID'];
$facven = $row['FactFecVen'];
$facsts = $row['FactSts'];
$faccen = $row['CentroID'];
$factot = $row['FactImporte'];
$facimp = $row['FactImpuesto'];
$factxt  = $row['FactTexto'];
$faccla = $row['ClaDocID'];;
$factc = $row['TipCam'];
$facmon = $row['MoneyID'];
$facref = $row['FacturaRef'];
$indimp = $row['IvaInd'];
$inddet = $row['DetInd'];
$cl_gasto = $row['claseID'];
$tipdoc = $row['TipDocu'];
$monexo = $row['MonExon'];
$valper = $row['MonPer'];
$indper = $row['PerInd'];
$feccon = $row['FactFeCon'];
				
			}
			$res->close();
			$mysqli->check_result();
		}
	}
?>

<?php 
if ($found){
?>
<div class="subTit">
<?php 
echo "Factura de Compras ".$fact." creado por ".$usrcre." el ".$faccre;
if ($facsts == 0) echo "&nbsp;[Activo]";
if ($facsts == 1) echo "&nbsp;[Anulado]";
if ($facsts == 2) echo "&nbsp;[Anulaci&oacute;n]";
?>
</div>
<?php
}
?>


<div>
<input type="button" onClick="nuevaFactura()" value="Nuevo">&nbsp;<input type="button" onClick="grabarFactura()" value="Grabar">&nbsp;
<input type="button" onClick="anularMiro()" value="Anular">&nbsp;
 <?php if ($found) {
	?>
      <input type="button" name="btn_fc_pag" id="btn_fc_pag" onclick="verDocPagFC();" class="enabled" value="Ver Documentos de Pago" />
      <?php  }
 ?>  
<!-- <input type="button" value="Listado" onClick="listarFacturas()"> -->
&nbsp;
<input type="text" name="t_fc_load" id="t_fc_load" onkeypress="if(event.keyCode==13)loadFactCom()" />
</div>
<table width="100%" border="0" cellspacing="0" cellpadding="0" id="tbl_dat_fac">
  <tr>
    <td>Clase de Documento</td>
    <td>
      <select name="cb_clfac" id="cb_clfac">
      <?php 
		$cladoc = 'FC';
		include('../Query_Min/getClaDocs.php');
		?>
      </select>    </td>
    <td><strong>Documento :</strong></td>
    <td><span id="sp_nofac" style="font-weight:bold;"></span></td>
  </tr>
  <tr>
    <td>Tipo Documento SUNAT:</td>
    <td colspan="3">
      <select style="width:50%" onchange="doFormatRef(null)" name="cb_rf_tdoc" id="cb_rf_tdoc">
      <option value='0' exp="2-5-6">Otros</option>
<option value='01' exp="2-4-6">Factura.</option>
<option value='02' exp="2-4-6">Recibo por Honorarios.</option>
<option value='03' exp="2-4-6">Boleta de Venta.</option>
<option value='04' exp="2-4-6">Liquidaci&oacute;n de compra.</option>
<option value='07' exp="2-4-6">Nota de cr&eacute;dito.</option>
<option value='08' exp="2-4-6">Nota de d&eacute;bito.</option>
<option value='09' exp="2-4-6">Gu&iacute;a de remisi&oacute;n Remitente.</option>
<option value='10' exp="2-4-6">Recibo por Arrendamiento.</option>
<option value='14' exp="2-4-10">Recibo por Servicios Publicos</option>
<option value='12' exp="2-4-10">Ticket</option>
<option value='20' exp="2-4-6">Comprobante de Retenci&oacute;n.</option>
<option value='21' exp="2-4-6">Conocimiento de embarque por el servicio de transporte de carga mar&iacute;tima.</option>
<option value='22' exp="2-4-6">Comprobante por Operaciones No Habituales.</option>
<option value='23' exp="2-4-6">P&oacute;lizas de Adjudicaci&oacute;n emitidas con ocasi&oacute;n del remate o adjudicaci&oacute;n de bienes por venta forzada, por los martilleros o las entidades que rematen o subasten bienes por cuenta de terceros.</option>
<option value='50' exp="2-3-7">Declaraci&oacute;n &Uacute;nica de Aduanas - DUA/ Declaraci&oacute;n Aduanera de Mercanc&iacute;as - DAM.</option>
<option value='51' exp="2-4-6">P&oacute;liza o DUI Fraccionada.</option>
<option value='91' exp="2-14">Comprobante de No Domiciliado.</option>
<option value='97' exp="2-4-6">Nota de Cr&eacute;dito - No Domiciliado. </option>
<option value='98' exp="2-4-6">Nota de D&eacute;bito - No Domiciliado.</option>
      </select>    </td>
  </tr>
  <tr>
    <td>Proveedor</td>
    <td>

      <select name="cbo_fac_prov" id="cbo_fac_prov">
      <?php 
	  include ('../Query_Min/getProveedores.php');
	  ?>
      </select>    </td>
    <td>Monto en Items:</td>
    <td><span id="sp_suma" style="font-weight:bold"></span> </td>
  </tr>
  <tr>
    <td>Referencia :</td>
    <td>
      <input name="t_reffac" type="text" onchange="doFormatRef(null);" class="clsReq" title="Referencia de Factura" id="t_reffac" size="25" maxlength="20" />    </td>
    <td>Importe(inc.Imp) :</td>
    <td><input name="t_monfac" type="text" id="t_monfac" class="qt clsReq" size="20" maxlength="15" title="Importe" onchange="mr(this);calcImp();calcSaldo();" />    </td>
  </tr>
  <tr>
    <td>Fecha Contable :</td>
    <td><input name="t_feccon" value="<?php echo $hoy;?>" type="text" class="tcal clsReq" id="t_feccon" size="20" maxlength="10" title="Fecha de Factura" /></td>
    <td>Saldo :</td>
    <td><input type="text" class="disabled qt" id="t_sald_fac" value="0.00" size="15" disabled="disabled" /></td>
  </tr>
  <tr>
    <td>Fecha Factura:</td>
    <td><input name="t_fecfac" type="text" class="tcal clsReq" id="t_fecfac" size="20" maxlength="10" title="Fecha de Factura" onchange="checkFecVen()" /></td>
    <td>Dias Vencimiento:</td>
    <td><select name="cb_diaven" id="cb_diaven" onchange="checkFecVen()">
      <option value="15">15 D&iacute;as</option>
      <option value="20">20 D&iacute;as</option>
      <option value="30">30 D&iacute;as</option>
      <option value="45">45 D&iacute;as</option>
      <option value="60">60 D&iacute;as</option>
      <option value="0">Otro</option>
    </select>
      <input name="t_diaven" class="noView qt" type="text" id="t_diaven" size="5" maxlength="3" onchange="checkFecVen()" /></td>
  </tr>
  <tr>
    <td>Fecha Vencimiento :</td>
    <td>
      <input name="t_fecven" type="text" class='tcal clsReq' id="t_fecven" size="20" maxlength="10" title="F.Vencimiento de Factura">    </td>
    <td>Monto Exonerado :</td>
    <td><input type="text" class="qt" id="t_monexo" name="t_monexo" size="20" onchange="mr(this);calcImp();" maxlength="10" /></td>
  </tr>
  <tr>
    <td>Local de Recepcion :</td>
    <td>
      <select name="cbo_centro" id="cbo_centro">
      <?php 
	  include ('../Query_Min/getCentros.php');
	  ?>
      </select>    </td>
    <td>Base imponible :</td>
    <td><input name="t_baseimp" type="text" class="qt" id="t_baseimp" disabled="disabled" onchange="mr(this);" size="20" maxlength="10" /></td>
  </tr>
  <tr>
    <td>Texto :</td>
    <td colspan="3">
      <input name="t_txtfac" class="clsReq" type="text" id="t_txtfac" size="60" maxlength="40" title="Texto de Factura">    </td>
    </tr>
  <tr>
    <td>Impuestos :</td>
    <td>
      <select name="cb_ind_imp" style="width:50px;" id="cb_ind_imp" onchange="calcImp()">
      <?php
	  $tipimp = 'IMP';
	   include ('../Query_Min/getIndicadores.php'); ?>
      </select>
      <input name="t_impfac" type="text" id="t_impfac" class="qt"  onchange="mr(this);calcImp();calcSaldo();" size="18" maxlength="10" title="Impuesto IGV" />
      <span class="onlyInput"><input name="chk_calc_aut" type="checkbox" id="chk_calc_aut" onchange="calcImp();calcSaldo();" checked="checked" />
    &nbsp;Calcular impuestos </span>   </td>
    <td><input type="checkbox" name="t_chkper" id="t_chkper" onchange="checkPercepcion()" />
      &nbsp;
      Aplica Percepci&oacute;n</td>
    <td ><input name="t_monper" disabled="disabled" type="text" id="t_monper" value="0.00" class="qt" onchange="mr(this);" size="15" maxlength="10" />
&nbsp;
      <input type="text" name="t_refper" tdoc="CP" onchange="doFormatRef(this);" exp="2-4-6" disabled="disabled" placeholder="Referencia" id="t_refper" />       </td>
  </tr>
  <tr>
    <td>Detracci&oacute;n :</td>
    <td>
    <select name="cb_ind_ret" style="width:200px;" id="cb_ind_ret" onchange="calcRet()">    
     <?php
	  $tipimp = 'DET';
	   include ('../Query_Min/getIndicadores.php'); ?>
       </select>&nbsp;<input type="text" class="disabled qt" id="sp_retfac" size="15" maxlength="15" disabled="disabled"/> </td>
    <td>Moneda :</td>
    <td><select name="cbo_moneda" id="cbo_moneda" onchange="changeMonFC()">
      <?php include ('../Query_Min/getMonedas.php'); ?>
    </select></td>
  </tr>
  <tr class="onlyInput">
    <td>&nbsp;</td>
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr class="onlyInput">
    <td>Datos de Compra :</td>
    <td colspan="3">
      <select name="cbo_tipreg" onChange="chgTipoReg()" id="cbo_tipreg">
      <option value="OC" selected="selected">Pedido de Compra</option>
      <option value="PR">Proveedor (m&aacute;s de una OC)</option>
      <option value="GA">Sin Referencia</option>
      </select>
      <span class="clsRefer">
      <input name="t_tipreg" type="text" class="" id="t_tipreg" onkeypress="if(event.keyCode==13)cargarDocumentos()" size="20" maxlength="10">
      <input type="submit" name="btn_cardoc" id="btn_cardoc" value="Cargar" onClick="cargarDocumentos()">
      <input name="chk_csti" type="checkbox" id="chk_csti" checked="checked" />
    &nbsp;Considerar Costos Indirectos    </span></td>
    </tr>
  <tr class='clsConcepto noView'>
    <td>Concepto de Compra :</td>
    <td colspan="2"><select id="cb_cl_gasto" style="width:200px; font-weight:bold;">
    <?php 
	if ($found){	
		$sql= "select * from tt_clase_gasto;";
		$res = $mysqli->query($sql);
		if($res){
		while($row=$res->fetch_assoc()){
		echo "<option value='".$row['claseID']."'>".$row['txtClase']."</option>";
		}
		$res->close();
		
		$mysqli->check_result();
		
		}
	}
	?>
    </select></td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td colspan="4"></hr></td>
  </tr>
  <tr>
    <td colspan="4">
    <div id="d_prov_oc" <?php if($buscar) echo 'class="noView"'; ?> ></div>    </td>
  </tr>
  <tr>
    <td colspan="4">
    <!-- Establecer Almac&eacute;n :
      <select id="cbo_gen_alm" onchange="setAlmacenes()">
        <?php 
	include ('../Query_Min/getAlmacenes.php');
	echo $combo;
	?>
      </select>   
      -->
      <hr />      </td>
  </tr>
  <tr>
    <td colspan="4">
    <table width="100%" class="tableIn" id="tbl_itm_fac" border="1" rules="all" cellspacing="0" cellpadding="0">
    <thead>
      <tr>
        <th align="center">
            <input onClick="CheckItems()" type="checkbox" name="chk_all" id="chk_all" checked='checked'></th>
        <th>Doc.Compra</th>
        <th>Posici&oacute;n</th>
        <th>Articulo</th>
        <th>Descripci&oacute;n</th>
        <th>Pr.Unitario</th>
        <th>Mon</th>
        <th>Cantidad</th>
        <th>Neto</th>
        <th>Almac&eacute;n</th>
        </tr>
      </thead>
       <tbody>
      <?php 
	  
	  if ($found){
	  $sql = "call sp_getFactCompDet('".$fact."');";
	  $res = $mysqli->query($sql);
	  	if ($res){
				while($row = $res->fetch_assoc()){
				$monitm = $monitm + $row['FactCompNeto'];
				?>
				<tr>
				<td><!-- <input class="chk" type="checkbox" checked="checked" disabled="disabled" /> --></td>
				<td><?php echo $row['OrdenNro'];?></td>
				<td><?php echo $row['OrdenPos'];?></td>
				<td><?php echo $row['ArticuloID'];?></td>
				<td><?php echo $row['FactCompTexto'];?></td>
				<td class="qt"><?php echo $row['FactCompPrUn'];?></td>
				<td class="qt"><?php echo $row['MoneyID'];?></td>
				<td class="qt"><?php echo $row['FactCompQta'];?></td>
				<td class="qt"><?php echo $row['FactCompNeto'];?></td>
				<td><?php echo $row['AlmacenID'];?></td>
				</tr>
				<?php 
				}
				$res->close();
				$mysqli->check_result();	
			}
		}
        ?>
      </tbody>
      <tfoot>
      <tr>
        <td>&nbsp;</td>
        <td>
          <input type="submit" class="onlyInput" name="btn_unchk" id="btn_unchk" onClick="delNoChecked()" value="Quitar Desmarcados">        </td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td><span id="sp_suma"></span></td>
        <td>&nbsp;</td>
        </tr>
      </tfoot>
    </table>    </td>
    </tr>
</table>
<script type="text/javascript">

<?php 
//$hoy = date('y-m-d');
//exit;
if (!$buscar){
?>
GEBI('t_fecfac').value = '<?php echo $hoy;?>';
GEBI('t_fecven').value = '<?php echo $hoy;?>';
<?php 
}
elseif ($found){
?>


$('#tbl_dat_fac input').disable();
$('#tbl_dat_fac select').disable();
GEBI('sp_nofac').innerHTML = '<?php echo $fact; ?>';
GEBI('cbo_fac_prov').value = '<?php echo $facpro?>';
GEBI('t_reffac').value = '<?php echo $facref?>';
GEBI('t_fecfac').value = '<?php echo $facfec?>';
GEBI('t_fecven').value = '<?php echo $facven?>';
GEBI('t_feccon').value = '<?php echo $feccon;?>';
GEBI('cbo_centro').value = '<?php echo $faccen?>';
GEBI('t_txtfac').value = '<?php echo $factxt?>';
GEBI('t_monfac').value = '<?php echo $factot?>';
GEBI('t_impfac').value = '<?php echo $facimp?>';
GEBI('cbo_moneda').value = '<?php echo $facmon?>';
GEBI('cb_ind_imp').value = '<?php echo $indimp; ?>';
GEBI('cb_ind_ret').value = '<?php echo $inddet;?>';
GEBI('cb_cl_gasto').value = '<?php echo $cl_gasto; ?>';
GEBI('cb_rf_tdoc').value = '<?php echo $tipdoc; ?>';
$(".onlyInput").addClass('noView');
GEBI('sp_suma').innerHTML = myRound('<?php echo $monitm;?>');
$(".clsConcepto").removeClass('noView');
GEBI("t_monexo").value = '<?php echo $monexo;?>';
//GEBI('sp_suma').innerHTML = '';
<?php
	if (trim($indper)!=""){
	?>
	GEBI('t_chkper').checked = true;
	GEBI('t_monper').value = '<?php echo $valper;?>';
	<?php 
	}

}
elseif ($buscar){
?>
showError('El Documento <?php echo $fact; ?> no existe');
<?php
}
?>


function validaFact(){
return checkDatos('#t_fecfac,#t_fecven,#t_monfac,#t_impfac,#t_reffac');
}

function nuevaFactura(){
//$('#tbl_dat_fac input[type=text]').val('');
//$('#tbl_dat_fac selected').not('.disabled').val('');
//$('#tbl_itm_fac tbody').html('');
loadPage('Procesos/MantFactura.php');
}

/*function validaFact(){
	if (myRound(GEBI('t_monfac').value)==0){
		showOk('Debe ingresar el Importe de Factura');
	}
	else if (myRound(GEBI('t_impfac').value)==0){
		showOk('Debe ingresar el importe de Impuesto');
	}
}*/

function grabarFactura(){
	if (!$("#tbl_dat_fac").checkInput()){
	return;
	}

	// Grabar OC
	var ret = false;
	var cl_gasto = '';
	
	if (GEBI('t_monfac').value <= 0){
	showError('El Importe de Factura debe ser mayor a cero');
	return;
	}
	
	if (!validaFact())
	return;
	
	var items = '';
	if (GEBI('cbo_tipreg').value != 'GA') {
		$('#tbl_itm_fac tbody tr').each(function(){		
			if (ret)
			return;
			
			var fila = $(this);
			var td = fila.find('td:first');
			if (td.find('input').is(':checked')){
			var oc = td.next().find('a').html();
			var pos = td.next().next().html();
			var txt = fila.find('.clsTxtPos').html();
			if (fila.hasClass('trFob')){
				var ctd = pInt($(this).find('.clsQtPen').val());
					if (ctd == 0){
					items = '';
					showOk('No se permiten Items de Factura con ctd. 0');
					ret = true;
					return;
					}			
				var alm = fila.find('select').val();
				// Solo considerar aquellos que estan marcados
				items = items + oc + '|' + pos + '|' + txt + '|' + ctd + '|' + alm + '#';
			}
			else {
				var net_cst = fila.find('.clsFcNet').val();
				var cla_cst = fila.find('.clsCod').attr('value');
				var pos = '0';
				items = items + oc + '|' + pos + '|' + txt + '|' + net_cst + '|' + cla_cst + '#';
			
			}
			
			
			}
			
		});
	}
	else {
		cl_gasto = GEBI('cb_cl_gasto').value;
	}
	
	if (ret)
	return;
	
	if ($.trim(items) != "" || $.trim(cl_gasto) !='')
	{
		sendData('Procesos/Opers/OperFact.php',
		{
			oper : 'save',
			t_tipdoc : GEBI('cb_rf_tdoc').value,
			t_fecfac : GEBI('t_fecfac').value,
			t_reffac : GEBI('t_reffac').value,
			t_fecven : GEBI('t_fecven').value,
			t_feccon : GEBI('t_feccon').value,
			cbo_centro : GEBI('cbo_centro').value,
			t_txtfac : GEBI('t_txtfac').value,
			cbo_moneda : GEBI('cbo_moneda').value,
			cbo_fac_prov : GEBI('cbo_fac_prov').value,
			t_monfac : GEBI('t_monfac').value,
			t_impfac : GEBI('t_impfac').value,
			t_monexo : GEBI('t_monexo').value,
			i_imp : GEBI('cb_ind_imp').value,
			i_det : GEBI('cb_ind_ret').value,
			i_per : (GEBI('t_chkper').checked?'P1':''),
			i_impper : GEBI('t_monper').value,
			t_refper : GEBI('t_refper').value,
			clase : cl_gasto,
			items : items
		}
		);		
	}
	else {
		showOk('No se han registrado Items por Facturar');
	}
}

function listarFacturas(){

}

function chgTipoReg(){
	GEBI('t_tipreg').value = ('');
	if (GEBI('cbo_tipreg').value == 'GA') {
	// Indica que corresponde a Gastos
	$('#tbl_itm_fac tbody tr').remove();
	$("#tbl_itm_fac").addClass('noView');
	$(".clsConcepto").removeClass('noView');
	$('.clsRefer').addClass('noView');
	
		if ($('.clsConcepto select option').length == 0){
			$('.clsConcepto select').html("<option>Cargando...</option>").loadx('Query_Min/getConceptosGast.php');
		}
	
	}
	else {
	$('.ClsRefer').removeClass('noView');
	$(".clsConcepto").addClass('noView');	
	$("#tbl_itm_fac").removeClass('noView');
	}
	
	GEBI('t_monfac').value = '0.00';
	GEBI('t_impfac').value = '0.00';
	
	
	
}

function cargarDocumentos(){
	var cstind = '';
	if (GEBI('chk_csti').checked){
	cstind = 'X';
	}

	if ($.trim(GEBI('t_tipreg').value) == '' ){
	showOk('Indique el Valor de busqueda');
	return;
	}
	GEBI('chk_all').checked = true;
	$('#tbl_itm_fac tbody').loadx('Query_Min/getDocCompras.php',
	{ 
	cbo_tipreg  : GEBI('cbo_tipreg').value,
	t_tipreg	:  GEBI('t_tipreg').value,
	cstind : cstind,
	moneda : GEBI('cbo_moneda').value
	},function(){
		calcDetFac();
	});
}

function delNoChecked(){
	var a = $('#tbl_itm_fac tbody tr').each(function(){
		if (!$(this).find('td:first input').is(':checked')){
			$(this).remove();
		}
	});
	calcDetFac();
}

function CheckItems(){
if (GEBI('chk_all').checked){
$('.clsFacChk').attr('checked','checked');
}
else {
$('.clsFacChk').removeAttr('checked','checked');
}
}

function calcDetFac(){
	//alert('');
	var tot_net = 0;
	$('#tbl_itm_fac tbody tr').each(function(){
			//return;
			var fila = $(this);
//alert(			fila.find('.clsFacChk').is(":checked"));
			if ( fila.find('.clsFacChk').is(":checked") ){
			
			var ctd = 0;
			var pre = 0;
			var dct = 0;
			var net = 0;
			
			if (fila.hasClass('trFob')){
			ctd = pInt(fila.find('.clsQtPen').val() );
			pre = pFloat(fila.find('.clsFcPru').html());
			dct = pFloat(fila.find('.clsFcDct').html());
			net = (ctd * (pre * (1 - (0.01 * dct))));
			fila.find('.clsFcNet').html(myRound(net));
			}
			else if(fila.hasClass('trCst')) {
			ctd = 1;
			pre = pFloat(fila.find('.clsFcNet').val());
			dct = 0;
			net = pre;
			}
			
			
			tot_net+=net;
			}
	});
	// Mostrar Monto sin IGV
	$('#sp_suma').html(myRound(tot_net));
	// Mostrar Monto con IGV	
	var iva =tot_net * pFloat($('#cb_ind_imp option:selected').attr('percent')) * 0.01;
	tot_net = tot_net + iva; 
	GEBI('t_monfac').value = myRound(tot_net);
	calcImp();
	calcSaldo();
}

function setAlmacenes(){
	$('.clsFacAlm').val(GEBI('cbo_gen_alm').value);
}

function loadFactCom(){
//alert('');
	var doc = GEBI('t_fc_load').value;
	loadPage('Procesos/MantFactura.php',{ factura : doc});
}

function calcSaldo(){
	var mon_auto = pFloat(GEBI('sp_suma').innerHTML);
	mon_auto = 0;
	var mon_manual = pFloat(GEBI('t_monfac').value);
	var mon_exo = pFloat(GEBI('t_monexo').value);
	var base = mon_manual - mon_exo;
	GEBI('t_baseimp').value = myRound(base);
	var migv = pFloat(GEBI('t_impfac').value);
	//alert (mon_auto + '/' + mon_manual + '/' + migv);
	var saldo = 0;
	
	saldo = ( mon_manual - mon_exo ) - ( mon_auto + migv );

	if (GEBI('cbo_tipreg').value == 'GA'){
	saldo = 0;
	}
	
	GEBI('t_sald_fac').value = myRound(saldo);	
}

function calcImp(){
	var iva  = 0;
//	var tot = pFloat($('#sp_suma').html());
	var monexo = pFloat(GEBI('t_monexo').value);
	var tot = pFloat(GEBI('t_monfac').value) - monexo;
	if (GEBI('chk_calc_aut').checked){
		iva = pInt($("#cb_ind_imp option:selected").attr('percent')) * 0.01;
		GEBI('t_impfac').disabled = true;	
		tot =  myRound(tot - myRound(tot / ( 1 + iva)));
		GEBI('t_impfac').value = tot;
	}
	else {
		GEBI('t_impfac').disabled = false;
	}
	calcSaldo();
	
}

function calcRet(){
//	var tot = pFloat($('#sp_suma').html());
	var tot = pFloat(GEBI('t_monfac').value);	
	var ret = pInt($("#cb_ind_ret option:selected").attr('percent')) * 0.01;
	$("#sp_retfac").val(myRound(ret * tot));
}

function anularMiro(){
	var doc = GEBI('sp_nofac').innerHTML;
	if (!confirm('Confirme para anular el documento '+doc))
	return;
	
	sendData('Procesos/Opers/OperFact.php',{
		oper : 'anularFC',
		factura : doc,
		motivo : ''
	});
}

function changeMonFC(){
	var mon = GEBI('cbo_moneda').value;
	$('#tbl_itm_fac tbody tr').each(function(){			
		var fila = $(this);
		var mon_itm = fila.find('.clsFcMon').html();
		if (mon_itm != mon){
		fila.remove();
		}
	});

}

function verDocPagFC(){
	var doc = GEBI('sp_nofac').innerHTML;
	loadPopup({ url : 'Consultas/ListDocPago.php', params : { oper : 'byFact', doc : doc } });
}

function doFormatRef(ctrl){
	var expre = "";
	var tdoc = "";
	if (ctrl==null){
		obj = GEBI('t_reffac');		
		expre = $("#cb_rf_tdoc option:selected").attr('exp');
		tdoc = $("#cb_rf_tdoc option:selected").val();
	}
	else{
		obj = ctrl;
		expre = $(ctrl).attr('exp');
		tdoc = $(ctrl).attr('tdoc');
	}
	
		 
		fs0 = expre.split("-");
		var txt = obj.value;
		fs1 = txt.split("-");
		
		if (fs1.length==2 && fs0.length ==3){
		fs1[2] = fs1[1];
		fs1[1] = fs1[0];
		fs1[0] = tdoc;
		}
		
		if (fs1.length==1 && fs0.length == 3){
		fs1[2] = fs1[0];
		fs1[1] = "0";
		fs1[0] = tdoc;
		}
		
		if (fs1.length==1){
		//fs1[2] = fs1[0];
		//fs1[1] = ;
		fs1[1] = txt;
		fs1[0] = tdoc;
		}
		
		if (fs0.length != fs1.length){
			obj.value = "";
			return;
		}
		
		var n_ref = '';
		
		for(x in fs0){
				if ($.isNumeric(fs1[x]) ){
				fs1[x] = fillZeros(fs1[x],pInt(fs0[x]) );
				}
				else{
				//fs1[x] = fs0[x];
				}
			if (x==0){
			fs1[x] = tdoc;
			n_ref = fs1[x]+'';
			}
			else {
			n_ref = n_ref + '-' + fs1[x];
			}
		}	
		obj.value = n_ref;
}

$("#cb_rf_tdoc option").each(function(){
	this.innerHTML = this.value + ' - ' + this.innerHTML;
});

function checkPercepcion(){
var chk = GEBI('t_chkper').checked;
GEBI('t_monper').disabled=!chk;
GEBI('t_refper').disabled=!chk;
if (chk){
	$("#t_monper,#t_refper").addClass('clsReq');
}
else {
	$("#t_monper,#t_refper").removeClass('clsReq');
}
}

function checkFecVen(){
	xfec = pInt(GEBI('t_diaven').value);
	GEBI('t_diaven').value
	var dia = GEBI('cb_diaven').value;
	if (dia ==0){
	dia = GEBI('t_diaven').value;
	}
	dia =pInt(dia);
	var fecfac = GEBI('t_fecfac').value;
	var fecven = AddDay(fecfac,dia);
	GEBI('t_fecven').value = fecven;
	
	if (GEBI('cb_diaven').value == 0){
	$('#t_diaven').removeClass('noView');
	}
	else {
	$('#t_diaven').addClass('noView');
	}
}
</script>
